package com.example.pageradapterdemo;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.example.pageradapterdemo.adapter.TabLayoutViewPagerAdapter;
import com.example.pageradapterdemo.fragment.SimpleFragment;
import com.example.pageradapterdemo.model.NewsType;
import com.example.pageradapterdemo.util.Constants;
import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class ViewPager2WithTabLayoutActivity extends AppCompatActivity {
    private TabLayout tabLayout;
    private ViewPager2 viewPager2;
    private List<String> titles;
    private List<Fragment> fragments;
    private TabLayoutViewPagerAdapter adapter;
    private static final OkHttpClient httpClient;
    public static final String NEWS_TYPE_URL = "/news/types";
    private Handler handler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg != null) {
                int what = msg.what;
                switch (what) {
                    case 0x001:
                        List<NewsType> newsTypes = (List<NewsType>) msg.obj;
                        fragments = new ArrayList<>();
                        titles = new ArrayList<>();
                        for (NewsType newsType : newsTypes) {
                            titles.add(newsType.getTypeName());
                            fragments.add(SimpleFragment.newInstance(newsType.getTypeId()));
                        }
                        adapter = new TabLayoutViewPagerAdapter(ViewPager2WithTabLayoutActivity.this,fragments);
                        viewPager2.setAdapter(adapter);
                        new TabLayoutMediator(tabLayout, viewPager2, new TabLayoutMediator.TabConfigurationStrategy() {
                            @Override
                            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                                tab.setText(titles.get(position));
                            }
                        }).attach();
                        break;
                }
            }
            return true;
        }
    });
    static{
        httpClient = new OkHttpClient();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_pager2_with_tab_layout);
        tabLayout = findViewById(R.id.tabLayout);
        viewPager2 = findViewById(R.id.viewPager2);
    }

    @Override
    protected void onStart() {
        super.onStart();
        getNewsTypes();
    }

    private void getNewsTypes(){
        Request request = new Request.Builder()
                .url(Constants.BASE_API.concat(NEWS_TYPE_URL))
                .addHeader("app_id",Constants.APP_ID)
                .addHeader("app_secret",Constants.APP_SECRET)
                .build();
        httpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseText = response.body().string();
                    if (responseText != null) {
                        JSONObject jsonObject = JSONObject.parseObject(responseText);
                        JSONArray jsonArray = jsonObject.getJSONArray("data");
                        List<NewsType> newsTypes = new ArrayList<>();
                        for (Object o : jsonArray) {
                            NewsType newsType = JSONObject.parseObject(o.toString(),NewsType.class);
                            newsTypes.add(newsType);
                        }
                        Message message = Message.obtain();
                        message.what = 0x001;
                        message.obj = newsTypes;
                        handler.sendMessage(message);
                    }
                }
            }
        });
    }
}